package com.gzs.learn.payment.pay.validate;

import com.google.common.collect.Maps;
import com.gzs.learn.common.util.JsonUtil;
import com.gzs.learn.inf.BaseResponseDto;
import com.gzs.learn.inf.ResponseCode;
import com.gzs.learn.payment.pay.ActionEnum;
import com.gzs.learn.payment.pay.ContextBase;
import com.gzs.learn.payment.pay.PaymentContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;

import static com.gzs.learn.common.util.SpringContextUtil.getBean;

@Component
@Slf4j
public class ValidateInvoker {
    private final Map<ActionEnum, BaseValidate> actions = Maps.newConcurrentMap();

    @PostConstruct
    public void init() {
        actions.put(ActionEnum.PAYMENT, getBean(PaymentValidate.class));
        actions.put(ActionEnum.PAYMENT_QUERY, getBean(PaymentQueryValidate.class));
        actions.put(ActionEnum.PAYMENT_CALLBACK, getBean(PaymentCallbackValidate.class));
        actions.put(ActionEnum.PAYMENT_NOTIFY, getBean(PaymentNotifyValidate.class));
        actions.put(ActionEnum.CLOSE, getBean(CloseValidate.class));
        actions.put(ActionEnum.REFUND, getBean(RefundValidate.class));
        actions.put(ActionEnum.REFUND_QUERY, getBean(RefundQueryValidate.class));
        actions.put(ActionEnum.REFUND_CALLBACK, getBean(RefundCallbackValidate.class));
        actions.put(ActionEnum.REFUND_NOTIFY, getBean(RefundNotifyValidate.class));
    }

    public BaseResponseDto<? extends Object> invoke(PaymentContext<ContextBase> paymentContext) {
        ActionEnum actionEnum = paymentContext.getActionEnum();
        BaseValidate baseValidate = actions.get(actionEnum);
        if (baseValidate == null) {
            log.warn("action:{} is null,context:{},default validate result is false", actionEnum,
                    JsonUtil.toJSONString(paymentContext));
            return BaseResponseDto.error(ResponseCode.SYS_ERROR.getCode(), "validate is null");
        }
        BaseResponseDto<? extends Object> responseDto = baseValidate.validate(paymentContext);
        return responseDto;
    }
}
